import { get, set } from "lodash-es";
import { htmlDecodeByRegExp, removeHtmlTag } from "./index";

// 定义一个基础映射对象
const baseI18nMap = {
  configLabel: "config.label",
  placeholder: "placeholder",
  description: "description",
  configRegListMessage: "config.regList[*].message",
  configFormulaValidateMessage: "config.formulaValidate[*].message"
};

// 定义一个映射对象
export const i18nKeyMap: Record<string, Record<string, string>> = {
  INPUT: {
    ...baseI18nMap,
    configDataTypeMessage: "config.dataType.message"
  },
  NUMBER: {
    ...baseI18nMap
  },
  TEXTAREA: {
    ...baseI18nMap
  },
  DATE: {
    ...baseI18nMap
  },
  RATE: {
    configLabel: "config.label"
  },
  UPLOAD: {
    ...baseI18nMap,
    buttonText: "config.buttonText"
  },
  IMAGE_UPLOAD: {
    ...baseI18nMap,
    buttonText: "config.buttonText"
  },
  SORT: {
    ...baseI18nMap,
    configOptionsLabel: "config.sortList[*].label"
  },
  SLIDER: {
    ...baseI18nMap
  },
  HORIZONTAL_INPUT: {
    ...baseI18nMap,
    input: "input"
  },
  SELECT: {
    ...baseI18nMap,
    configOptionsLabel: "config.options[*].label"
  },
  MULTIPLE_SELECT: {
    ...baseI18nMap,
    configOptionsLabel: "config.options[*].label"
  },
  CASCADER: {
    ...baseI18nMap,
    configOptionsLabel: "config.options[*].label"
  },
  RADIO: {
    ...baseI18nMap,
    configOptionsLabel: "config.options[*].label",
    quotaBlankWarning: "quotaBlankWarning"
  },
  CHECKBOX: {
    ...baseI18nMap,
    configOptionsLabel: "config.options[*].label",
    quotaBlankWarning: "quotaBlankWarning"
  },
  IMAGE_SELECT: {
    ...baseI18nMap,
    configOptionsLabel: "config.options[*].label"
  },
  SIGN_PAD: {
    ...baseI18nMap,
    tips: "textConfig.tips",
    clearBtnText: "textConfig.clearBtnText",
    confirmBtnText: "textConfig.confirmBtnText",
    backBtnText: "textConfig.backBtnText",
    reSignBtnText: "textConfig.reSignBtnText"
  },
  PROVINCE_CITY: {
    ...baseI18nMap
  },
  INPUT_MAP: {
    ...baseI18nMap
  },
  PHONE_VERIFICATION: {
    ...baseI18nMap
  },
  NPS: {
    ...baseI18nMap,
    max: "table.copyWriting.max",
    min: "table.copyWriting.min"
  },
  SUB_FORM: {
    configLabel: "config.label"
  },
  OCR: {
    configLabel: "config.label"
  },
  SCAN: {
    ...baseI18nMap
  },
  RANDOM_NUMBER: {
    configLabel: "config.label"
  },
  FUNCTION_CALC: {
    configLabel: "config.label"
  },
  GOODS_SELECT: {
    ...baseI18nMap,
    goodsName: "goodsList[*].goodsName"
  },
  CONFIRMATION_CODE: {
    configLabel: "config.label"
  },
  FACE_IDENTIFY: {
    configLabel: "config.label"
  },
  RICH_TEXT: {
    configLabel: "config.label"
  },
  VALIDATE_CODE: {
    configLabel: "config.label"
  },
  CHECK_ITEM: {
    ...baseI18nMap,
    checkItemLabel: "options[*].label",
    btnListLabel: "btnList[*].label"
  },
  RESERVE_DAY: {
    ...baseI18nMap,
    reserveProjectName: "reserveProjectList[*].name"
  },
  RESERVE_TIME_RANGE: {
    ...baseI18nMap,
    reserveProjectName: "reserveProjectList[*].name"
  },
  MATRIX_INPUT: {
    ...baseI18nMap,
    rowLabel: "table.rows[*].label",
    columnLabel: "table.columns[*].label"
  },
  MATRIX_SELECT: {
    ...baseI18nMap,
    rowLabel: "table.rows[*].label",
    columnLabel: "table.columns[*].label"
  },
  MATRIX_SCALE: {
    ...baseI18nMap,
    rowLabel: "table.rows[*].label",
    max: "table.copyWriting.max",
    min: "table.copyWriting.min"
  },
  MATRIX_SLIDER: {
    ...baseI18nMap,
    rowLabel: "table.rows[*].label"
  },
  MATRIX_DROPDOWN: {
    ...baseI18nMap,
    rowLabel: "table.rows[*].label",
    columnLabel: "table.columns[*].label",
    optionsLabel: "options[*].label"
  },
  TABLE_SELECT: {
    ...baseI18nMap,
    rowLabel: "table.rows[*].label",
    columnLabel: "table.columns[*].label",
    tableOptions: "tableOptions"
  },
  PAGINATION: {
    ...baseI18nMap,
    prevBtnText: "textConfig.prevBtnText",
    nextBtnText: "textConfig.nextBtnText"
  },
  DIVIDER: {
    configLabel: "config.label"
  },
  BUTTON: {
    ...baseI18nMap,
    content: "content"
  },
  IMAGE: {
    configLabel: "config.label"
  },
  IMAGE_CAROUSEL: {
    ...baseI18nMap,
    optionsLabel: "options[*].label"
  },
  DESC_TEXT: {
    ...baseI18nMap,
    content: "content"
  },
  USER_SELECT: {
    configLabel: "config.label"
  },
  DEPT_SELECT: {
    configLabel: "config.label"
  }
};

// 所有可用的语言列表
export const allLanguages = [
  { name: "简体中文", code: "zh-CN", default: true },
  { name: "English", code: "en-US", default: false },
  { name: "繁體中文", code: "zh-TW", default: false },
  { name: "日本語", code: "ja-JP", default: false },
  { name: "한국어", code: "ko-KR", default: false },
  { name: "Deutsch", code: "de-DE", default: false },
  { name: "Français", code: "fr-FR", default: false }
];

export const FORM_LANG_KEY = "formLang";

// 获取对应的文案
export const getFormLangContent = (lang: string, key: string, langContent: Record<string, Record<string, string>>) => {
  if (!langContent || !lang) {
    return "";
  }
  const langMap = langContent[lang];
  if (langMap) {
    return langMap[key];
  }
  return null;
};

// 设置文案到表单基础信息中
export const setFormLangContent = (formInfo: any, lang: string, langContent: Record<string, any>) => {
  if (langContent) {
    const title = getFormLangContent(lang, "name", langContent);
    const description = getFormLangContent(lang, "description", langContent);
    if (title) {
      formInfo.title = title;
      // 设置标题
      document.title = htmlDecodeByRegExp(removeHtmlTag(formInfo.title));
    }
    if (description) {
      formInfo.description = description;
    }
  }
};

// 获取当前表单默认语言
export const getFormDefaultLang = (formKey: string, defaultLang: string) => {
  const lang = sessionStorage.getItem(FORM_LANG_KEY + formKey);
  if (lang) {
    return lang;
  }
  return defaultLang || "zh-CN";
};

/**
 * 转换到语言结构json 保存到后端时使用
 * @param item 题目
 * @param lang 当前语言
 * @return 把文案转到语言结构json
 */
export const convertLangContent = (item: any, lang: string) => {
  // 某个语言的具体配置
  const keyMap = i18nKeyMap[item.typeId as keyof typeof i18nKeyMap];
  const langContent: Record<string, string | Record<string, string>> = {};
  if (keyMap) {
    Object.keys(keyMap).forEach(key => {
      const valuePath = keyMap[key];
      // 如果包含[*]，则表示是数组 例如选项题目
      if (valuePath.includes("[*]")) {
        // 根据[*]拆分
        const [prefix, suffix] = valuePath.split("[*].");
        const valueList = get(item, prefix);
        if (Array.isArray(valueList)) {
          let subLangContent: Record<string, string> = {};
          valueList.forEach(vItem => {
            const subKey = get(vItem, "value") || get(vItem, "id");
            if (subKey) {
              subLangContent[subKey] = get(vItem, suffix);
            }
            // 如果存在child，则递归处理 例如级联
            const childList = get(vItem, "children");
            recursiveHandleChildren(childList, subLangContent, suffix, subKey);
          });
          langContent[key] = subLangContent;
        }
      } else {
        langContent[key] = get(item, valuePath);
      }
    });
    // 如果子表单 还需要处理里面得组件
    if (item.typeId === "SUB_FORM") {
      handleSubFormLangContent(item, lang);
    }
  }
  return langContent;
};

/**
 * 递归处理
 */
export const recursiveHandleChildren = (childList: any[], langContent: Record<string, any>, suffix: string, subKey: string) => {
  if (!childList) {
    return;
  }
  if (Array.isArray(childList)) {
    childList.forEach(vItem => {
      let finalSubKey = subKey;
      const recursiveSubKey = get(vItem, "value") || get(vItem, "id");
      if (recursiveSubKey) {
        finalSubKey += "_" + recursiveSubKey;
        langContent[finalSubKey] = get(vItem, suffix);
      }
      // 如果存在child，则递归处理
      const childList = get(vItem, "children");
      recursiveHandleChildren(childList, langContent, suffix, finalSubKey);
    });
  }
};

// 特殊处理子表单的文案
export const handleSubFormLangContent = (item: any, lang: string) => {
  const subFormList = get(item, "childList");
  // 子题目
  if (Array.isArray(subFormList)) {
    subFormList.forEach(subItem => {
      let currentItemLangContent = tempLangContent[subItem.config!.formId] || subItem.langContent;
      if (!currentItemLangContent) {
        currentItemLangContent = {};
      }
      currentItemLangContent[lang] = convertLangContent(subItem, lang);
      // 更新到题目
      subItem.langContent = currentItemLangContent;
      // 更新到临时缓存
      tempLangContent[subItem.config!.formId] = currentItemLangContent;
    });
  }
};

/**
 * 递归解析
 */
export const recursiveParseChildren = (item: string, langContent: Record<string, any>, suffix: string, subKey: string) => {
  const childList = get(item, "children");
  if (Array.isArray(childList)) {
    childList.forEach(vItem => {
      let finalSubKey = subKey;
      const recursiveSubKey = get(vItem, "value") || get(vItem, "id");
      if (recursiveSubKey) {
        finalSubKey += "_" + recursiveSubKey;
        if (langContent[finalSubKey]) {
          set(vItem, suffix, langContent[finalSubKey]);
        }
      }
      // 如果存在child，则递归处理
      const childList = get(vItem, "children");
      if (childList) {
        recursiveParseChildren(vItem, langContent, suffix, finalSubKey);
      }
    });
  }
};

// 解析子表单的文案
const parseSubFormLangContent = (item: any, lang: string) => {
  const subFormList = get(item, "childList");
  if (Array.isArray(subFormList)) {
    subFormList.forEach(subItem => {
      // 加载多语言文件 优先取本地缓存 在编辑时缓存有值 这里就值|一下
      parseLangContent(subItem, lang, tempLangContent[subItem.config!.formId] || subItem.langContent);
    });
  }
};

/**
 * 解析语言到json定义
 * @param jsonItem 题目定义\
 * @param lang 语言
 *
 */
export const parseLangContent = (jsonItem: any, lang: string, langContent: Record<string, any>) => {
  if (!langContent) {
    return;
  }
  const keyMap = i18nKeyMap[jsonItem.typeId as keyof typeof i18nKeyMap];
  const currentLangContent = langContent[lang];
  if (!currentLangContent) {
    return;
  }
  if (keyMap) {
    Object.keys(keyMap).forEach(key => {
      const langValue = currentLangContent[key];
      const path = keyMap[key];
      if (path.includes("[*]")) {
        // 如果包含[*]，则表示是数组 例如选项题目
        const [prefix, suffix] = path.split("[*].");
        // 找到选项
        const value = get(jsonItem, prefix);
        // 文案值
        if (Array.isArray(value)) {
          value.forEach(item => {
            // console.log(item);
            const value = langValue[get(item, "value") || get(item, "id")];
            set(item, suffix, value);
            const childList = get(item, "children");
            if (childList) {
              recursiveParseChildren(item, currentLangContent[key], suffix, item.value);
            }
          });
        }
      } else {
        const value = currentLangContent[key];
        set(jsonItem, path, value);
      }
    });
    // 如果子表单 还需要处理里面得组件
    if (jsonItem.typeId === "SUB_FORM") {
      parseSubFormLangContent(jsonItem, lang);
    }
  }
};

// 临时存储当前全部语言的配置
// {“题目id”:{“语言”:{“配置key”:“配置值”}}}

export let tempLangContent: Record<string, any> = {};

export const resetTempLangContent = () => {
  tempLangContent = {};
};
